var districtData = new Bloodhound({
    local: [],
    identify: function (obj) {
        if (obj) return obj.code;
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("fullName", "fullJP", "fullPinyin", "code", "cityName", "cnPinyinAll", "cnPinyinHead", "areaName", "anPinyinAll", "anPinyinHead")
});
$.ajax({
    url: contextPath + "/district/findToArea.json",
    type: "GET",
    contentType: "application/json"
}).done(function (orgData) {
    districtData.add(orgData);
});
(function ($) {
    var kendo = window.kendo, ui = kendo.ui;
    var val = "";
    var DistrictSelect = kendo.ui.Widget.extend({
        _uid: null,
        _v: null,
        input: null,
        state: "empty",
        dataBlood: null,
        init: function (element, options) {
            var that = this;
            that.dataBlood =districtData;
            kendo.ui.Widget.fn.init.call(this, element, options);
            that.input = $(element).clone();
            $(element).bind("change",function(e){
                var v = $(this).val();
                that.change(v);
            });
            that.input.attr("id", $(element).attr('id') + "_typeahead");
            that.input.addClass("k-textbox").appendTo($(element).parent());
            $(element).appendTo($(element).parent());
            $(element).attr("type", "hidden");
            that.input.typeahead({highlight: true, minLength: 0}, {
                display: 'fullName',
                val: "code",
                limit: 100,
                source: that.dataBlood
            }).bind('typeahead:select', function (ev, selectedItem) {
                that.onSelect(selectedItem)
            }).bind('typeahead:autocomplete', function (ev, selectedItem) {
                that.onSelect(selectedItem)
            }).bind('typeahead:open', function (ev) {
            }).bind('blur', function (ev) {
                $(this).trigger("typeahead:change")
            }).bind('focus', function (ev) {
                // that.bindDataBlood();
            }).bind('typeahead:change', function (ev, value) {
                if (value === "") {
                    $(element).val("");
                    that.input.val("");
                    that.input.trigger("change");
                    $(element).trigger("change");
                }
                var values = that.dataBlood.get($(element).val());
                if (values.length == 1) {
                    that.input.val(values[0].fullName)
                }
            })
        },
        concatName: function (children, parentName, parentPH) {
            if (children && children.length > 0) {
                for (var i = 0; i < children.length; i++) {
                    children[i].fullName = parentName + children[i].name;
                    children[i].fullJP = parentPH + children[i].namePinyinHead;
                    this.data.push(children[i]);
                    if (children[i].children && children[i].children.length > 0) {
                        this.concatName(children[i].children, children[i].fullName, children[i].fullJP)
                    }
                }
            }
        },
        onSelect: function (selectedItem) {
            var that = this;
            $(that.element).val(selectedItem.code).trigger('change');
            that.bindArea(selectedItem.code);
            if (selectedItem.streetCode) {
                that.state = "street";
            } else if (selectedItem.areaCode) {
                that.state = "area";
                $.ajax({
                    url: contextPath + "/district/findStreet/" + selectedItem.areaCode,
                    type: "GET",
                    contentType: "application/json"
                }).done(function (result) {
                    $.each(result, function (i, item) {
                        item.fullName = selectedItem.fullName + item.streetName;
                        item.fullJP = selectedItem.fullName + item.snPinyinHead;
                        item.fullPinyin = selectedItem.fullName + item.snPinyinAll;
                    });
                    that.dataBlood.add(result);
                    that.open();
                })
            } else if (selectedItem.cityCode) {
                that.state = "city";
            } else if (selectedItem.provinceCode) {
                that.state = "province";
            }
        },
        open: function () {
            var ev = $.Event("keydown");
            ev.keyCode = ev.which = 32;
            this.input.typeahead('val', this.input.typeahead('val').trim() + " ").trigger(ev)
        },
        options: {name: "DistrictSelect"},
        getItem: function () {
            return this.dataBlood.get($(this.element).val(v))[0];
        },
        bindDataBlood: function () {
            var that = this;
            if (districtData.local.length === 0) {
                $.ajax({
                    url: contextPath + "/district/findToArea",
                    type: "GET",
                    contentType: "application/json",
                    async: false
                }).done(function (orgData) {
                    districtData.add(orgData);
                })
            }
        },
        bindArea: function (v) {
            var that = this;
            if (v.length !== 6 && v.length !== 9)return;
            var item = this.dataBlood.get(v)[0];
            if (item) {
                $(that.options.province).val(item.provinceName).trigger("change");
                $(that.options.city).val(item.cityName).trigger("change");
                $(that.options.area).val(item.areaName).trigger("change");
                $(that.options.street).val(item.streetName).trigger("change");
            }
        },
        value: function (v) {
            var that = this;
            if (v == null || v == undefined) {
                return $(that.element).val();
            } else {
                if (v === "" || v == null) {
                    $(that.element).val("").trigger('change');
                    that.input.val("");
                    that.state = "empty";
                } else {
                    $(that.element).val(v).trigger('change');
                    if (v.length === 9) {
                        var parent = that.dataBlood.get(v.substr(0, 6))[0] || that.dataBlood.get(v.substr(0, 4) + "00")[0];
                        var parentName = parent.fullName;
                        $.ajax({
                            url: contextPath + "/district/findStreet/" + v.substr(0, 6),
                            type: "GET",
                            contentType: "application/json",
                        }).done(function (result) {
                            $.each(result, function (i, item) {
                                item.fullName = parentName + item.streetName;
                                item.fullJP = parentName + item.snPinyinHead;
                                item.fullPinyin = parentName + item.snPinyinAll;
                            });
                            that.dataBlood.add(result)
                            if (that.dataBlood.get(v).length === 1) {
                                that.input.val(that.dataBlood.get(v)[0].fullName);
                                that.input.trigger("change");
                            }
                        })
                    }
                    if (that.dataBlood.get(v).length === 1) {
                        that.input.val(that.dataBlood.get(v)[0].fullName);
                        that.input.trigger("change");
                    }
                }
                that.bindArea(v);
            }
        },
        change: function (v) {
            var that = this;
            if (v == null || v == undefined) {
                return $(that.element).val();
            } else {
                if (v === "" || v == null) {
                    that.input.val("");
                    that.state = "empty";
                } else {
                    if (v.length === 9) {
                        var parent = that.dataBlood.get(v.substr(0, 6))[0] || that.dataBlood.get(v.substr(0, 4) + "00")[0];
                        var parentName = parent.fullName;
                        $.ajax({
                            url: contextPath + "/district/findStreet/" + v.substr(0, 6),
                            type: "GET",
                            contentType: "application/json",
                        }).done(function (result) {
                            $.each(result, function (i, item) {
                                item.fullName = parentName + item.streetName;
                                item.fullJP = parentName + item.snPinyinHead;
                                item.fullPinyin = parentName + item.snPinyinAll;
                            });
                            that.dataBlood.add(result)
                            if (that.dataBlood.get(v).length === 1) {
                                that.input.val(that.dataBlood.get(v)[0].fullName).trigger("change");
                            }
                        })
                    }
                    if (that.dataBlood.get(v).length === 1) {
                        that.input.val(that.dataBlood.get(v)[0].fullName).trigger("change");
                    }
                }
                that.bindArea(v);
            }
        },
        selectItem: function () {
            var that = this;
            var district = {};
            if ($(that.element).val()) district.code = that.dataBlood.get($(that.element).val())[0];
            return district;
        }
    });

    ui.plugin(DistrictSelect);


})(jQuery);